<template>
	<view>
		<view style="height: 80rpx;"></view>
		<view class="head">
			<view class="title">我的访客邀请码</view>
			<view class="head_left_bottom"></view>
			<view class="head_right_bottom"></view>
		</view>
		<view class="body">
			<!-- <image class="body-logo" src="../../static/logo_y.png" mode=""></image>
			<image class="code-img" :src="code" mode=""></image> -->
			<ikun-qrcode
				width="444"
				height="444"
				unit="rpx"
				:color="whatColor"
				:data="code"
			/>
			<view class="body_left_bottom"></view>
			<view class="body_right_bottom"></view>
		</view>
		<view class="door-setting">授权门禁点：{{doorName}}</view>
		<view v-if="info.type==1 || info.type==2" class="task-go">请去往{{info.deptIdName}}</view>
		<view class="foot-title">访客邀请码是通行凭证，请{{toName=='环安'?'先':''}}向<span style="color: red;">{{toName}}</span>出示此码</view>
		<u-row v-if="info.type==3" gutter="32" class="foot-btn">
			<u-col span="6">
				<u-button type="error" :disabled="whatColor=='red'?true:false" @click="cancel">结束来访</u-button>
			</u-col>
			<u-col span="6">
				<u-button type="primary"  @click="showTask=true">施工任务</u-button>
			</u-col>
			<!-- <u-col span="4">
				<u-button type="primary" :disabled="!canShare || info.vnum==1?true:false" @click="copyShare">复制分享</u-button>
			</u-col> -->
		</u-row>
		<u-row v-if="info.type==1 || info.type==2" gutter="32" class="foot-btn">
			<u-col v-if="whatColor!='red'" span="6">
				<u-button type="error" @click="cancel">结束来访</u-button>
			</u-col>
			<u-col :span="whatColor!='red'?6:12">
				<u-button type="primary" :disabled="!canShare || info.vnum==1?true:false" @click="copyShare">复制分享</u-button>
				<!-- <u-button type="primary" :disabled="canShare?true:false" open-type="share">邀请同事</u-button> -->
			</u-col>
		</u-row>
		<u-row v-if="info.type>3" gutter="32" class="foot-btn">
			<u-col v-if="whatColor!='red'" span="12">
				<u-button type="error" @click="cancel">结束来访</u-button>
			</u-col>
		</u-row>
		<u-modal v-model="show" @confirm="confirm" @cancel="cancelNo" show-cancel-button content="确定吗？结束来访后需重新申请"></u-modal>
		<u-modal v-model="showTask" title="和您相关施工任务" confirm-text="立即开干" cancel-text="结束来访" @confirm="confirmGo" @cancel="cancel" :show-confirm-button="isSing" :show-cancel-button="isSing">
			<view class="slot-content">
				<u-checkbox-group wrap @change="checkboxGroupChange">
					<u-checkbox v-model="item.checked" v-for="(item, index) in TaskList" :key="index" :name="item.vreason" :disabled="item.isDis">
						{{ item.vreason }}
					</u-checkbox>
				</u-checkbox-group>
				<view v-if="!isSing">请阅读<span style="color: blue;" @tap="openSn">《安全告知书》</span>并签字</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				reasons: '',
				haImg: '',
				isSing: true,
				TaskList: [],
				showTask: false,
				canShare: false,
				info: {},
				show: false,
				code:'',
				whatColor: 'green',
				doorName: '',
				toName: '门卫',
				shareId: '',
				intervalId: null, // 新增属性以保存定时器ID
				intervalId2: null // 新增属性以保存定时器ID2
			}
		},
		onLoad(options) {
			const elements = options.content.split(',')
			this.code = elements[0]
			if(elements[3]) {
				this.shareId = elements[3]
			}
			// this.setColor()
			this.whatColor = elements[1]==10 || elements[1]==25?'green':elements[1]==30?'blue':elements[1]==45?'black':'red'
			this.toName = elements[2]==3 && elements[1]==10?'环安':'门卫'
			this.getDoorSetting(elements[2])
			
			if(this.whatColor=='green' || this.whatColor=='black') {
				if(elements[2]==3) {
					this.showTask = true
				}
			}
			
			const id = this.shareId==''?this.code:this.shareId
			this.existNum(id)
		},
		onShow() {
			uni.$on('page-msg', this.pageMsg)
		},
		// onShareAppMessage(res) {
		// 	const id = this.shareId==''?this.code:this.shareId
		// 	if (res.from === 'button') {// 来自页面内分享按钮
		// 	  console.log(res.target)
		// 	}
		// 	return {
		// 	  title: '邀请同事绑定一起来访',
		// 	  path: '/pages/my/share?id='+id
		// 	}
		// },
		mounted() {
			this.initData()
			// 设置定时器每隔一定时间刷新二维码
			this.intervalId = setInterval(() => {
				this.refreshQRColor()
			}, 10000); // 每10秒刷新一次，可以根据需要调整
			
			// 设置定时器每隔一定时间检查
			this.intervalId2 = setInterval(() => {
				if(this.whatColor=='green' || this.whatColor=='black') {
					if(this.info.type==3) {
						this.showTask = true
					}
				}
			}, 60 * 1000 * 5); // 每5分钟刷新一次，可以根据需要调整
		},
		beforeDestroy() {
			// 清除定时器
			if (this.intervalId) {
				clearInterval(this.intervalId);
			}
			if (this.intervalId2) {
				clearInterval(this.intervalId2);
			}
		},
		methods: {
			cancelNo() {
				if(this.info.type==3) {
					if(this.whatColor=='green' || this.whatColor=='black') {
						this.showTask = true
					}
				}
			},
			checkboxGroupChange(e) {
				console.log('看看',e);
				const arrA  = this.info.vreason ? this.info.vreason.split('|') : [];
				const arrC = e.filter(item => !arrA.find(element => element === item));
				console.log('卡控',arrC)
				if(arrC.length>0){
					this.isSing = false
				}else{
					this.isSing = true
				}
			},
			pageMsg(data) {
				this.isSing = data.isSing
				this.haImg = data.haImg
			},
			openSn() {
				const arr = this.TaskList.filter(item => item.checked==true)
				var reasons = ''
				arr.map((val, index) => {
					if(index === arr.length - 1) {
						reasons += val.vreason
					}else {
						reasons += val.vreason+'|'
					}
				})
				
				let arrA = this.info.vreason ? this.info.vreason.split('|') : [];
				let arrB = reasons.split('|');
				// 使用 Set 去除重复元素
				let arrC = Array.from(new Set([...arrA, ...arrB]));
				// 重新合成字符串
				let cc = arrC.join('|');
				uni.navigateTo({
					url:'/pages/my/safeNotice?vcompany='+this.info.vcompany+'&reasons='+cc+'&visitor='+this.info.visitor+'&idCard='+this.info.idCard
				})
			},
			confirmGo() {
				if(!this.isSing) {
					this.showTask = true
					return this.$u.toast('请先阅读告知书并签字')
				}
				const arr = this.TaskList.filter(item => item.checked==true)
				var reasons = ''
				var staffs = ''
				var iphones = ''
				arr.map((val, index) => {
					if(index === arr.length - 1) {
						reasons += val.vreason
						staffs += val.staff
						iphones += val.iphone
					}else {
						reasons += val.vreason+'|'
						staffs += val.staff+'|'
						iphones += val.iphone+'|'
					}
				})
				if(reasons==''){
					this.showTask = true
					return this.$u.toast('请勾选任务')
				}
				let arrA = this.info.vreason ? this.info.vreason.split('|') : [];
				let arrB = reasons.split('|');
				// 使用 Set 去除重复元素
				let arrC = Array.from(new Set([...arrA, ...arrB]));
				// 重新合成字符串
				let cc = arrC.join('|');
				this.$u.post('/visitlogextend/update',{...this.info,vreason:cc,staff:staffs,iphone:iphones,haImg:this.haImg==''?this.info.haImg:this.haImg}).then(res => {
					if(res.code==200){
						this.$u.toast('成功')
					}else{
						this.showTask = true
						return this.$u.toast(res.message)
					}	
				}).catch(err => {
					this.showTask = true
					return this.$u.toast(err)
				})
			},
			getFlowVcompany(vcompany) {
				this.$u.post('/visitlogextend/PageFlowVcompany/'+vcompany).then(res => {
					if(res.code==200){
						const vreasonArr = this.info.vreason ? this.info.vreason.split('|') : [];
						this.TaskList = res.result.map(item => {
							const checked = vreasonArr.some(reason => item.vreason == reason);
							return {...item,checked: checked,isDis: checked};
						}).filter(item => item.personlistString.includes(this.info.visitor))
					}else{
						this.$u.toast('获取施工项目失败',res.message)
					}	
				}).catch(err => {
					this.$u.toast('获取施工项目异常',err)
				})
			},
			copyShare() {
			  const id = this.shareId==''?this.code:this.shareId
			  uni.setClipboardData({
			  	data: 'https://scm.emcks.com:55081/#/pages/my/share?id='+id,
			  	success: function () {
			  		uni.showModal({
			  			title: '复制成功',
			  			content: '已复制到粘贴板，可前往其他应用粘贴发送给好友一起来访。', 
			  			showCancel:false,
			  			success: function(res) {
			  				if (res.confirm) {											 
			  					//console.log('用户点击确定');
			  				} else if (res.cancel) {
			  					//console.log('用户点击取消');
			  				}
			  			}
			  		});
			  	}
			  });
			},
			existNum(id) {
				this.$u.get('/visitlog/getexistshare/'+id).then(res => {
					if(res.code==200){
						if(res.result) {
							const num = res.result.vnum - res.result.count - 1
							if(num>0) {
								this.canShare = true
							}else{
								this.canShare = false
							}
						}else{
							this.canShare = true
						}
					}else{
						this.$u.toast(res.message)
						this.canShare = false
					}
				}).catch(err => {
					this.$u.toast(err)
					this.canShare = false
				})
			},
			confirm() {
				if(this.info.type==3) {
					if(this.whatColor=='green' || this.whatColor=='black') {
						this.showTask = true
					}
				}
				this.$u.post('/visitLogExtend/update',{...this.info,status:50}).then(res => {
					if(res.code==200){
						this.getDetail()
						this.$u.toast('结束来访成功')
						uni.redirectTo({
							url: '/pages/index/index'
						})
					}else{
						this.$u.toast('删除失败',res.message)
					}	
				}).catch(err => {
					this.$u.toast('删除异常', err)
				})
			},
			cancel() {
				this.refreshQRColor()
				this.show = true
			},
			refreshQRColor() {
				// 这里可以调用相应接口更新二维码颜色
				this.$u.get('/visitlog/detail',{
					id:this.code
				}).then(res => {
					if(res.code == 200) {
						this.info = res.result
						this.whatColor = res.result.status==10 || res.result.status==25?'green':res.result.status==30?'blue':res.result.status==45?'black':'red'
						this.toName = res.result.type==3 && res.result.status==10?'环安':'门卫'
						if(res.result.type>3) {
							this.whatColor = res.result.status==30?'blue':'purple'
						}
					} else {
						this.$u.toast('刷新失败', res.message);
					}
				}).catch(err => {
					this.$u.toast('请求异常', err);
				});
			},
			initData() {
				// 这里可以调用相应接口更新二维码颜色
				this.$u.get('/visitlog/detail',{
					id:this.code
				}).then(res => {
					if(res.code == 200) {
						this.info = res.result
						this.whatColor = res.result.status==10 || res.result.status==25?'green':res.result.status==30?'blue':res.result.status==45?'black':'red'
						this.toName = res.result.type==3 && res.result.status==10?'环安':'门卫'
						if(res.result.type==3) {
							this.getFlowVcompany(res.result.vcompany)
						}
						if(res.result.type>3) {
							this.whatColor = res.result.status==30?'blue':'purple'
						}
					} else {
						this.$u.toast('刷新失败', res.message);
					}
				}).catch(err => {
					this.$u.toast('请求异常', err);
				});
			},
			getDoorSetting(type) {
				this.$u.get('/visitlogextend/loaddoorsettings').then(res => {
					if(res.code==200){
						const found = res.result.find(item => item.type == type)
						if (found && found.children) {
							this.doorName =  found.children.map(child => child.name).join('、')
						}
					}else{
						this.$u.toast('请求失败',res.message)
					}	
				}).catch(err => {
					this.$u.toast('请求异常',err)
				})
			},
			setColor(elements) {
				// const elements = this.code.split(','); // 将字符串通过逗号分割成数组
				
				// 获取时间字符串并进行解码
				const timeString = decodeURIComponent(elements[2]); // 解码的时间字符串
				const eventTime = new Date(timeString); // 转换为 Date 对象
				
				const currentTime = new Date();	// 获取当前时间
				
				// 计算时间差（以分钟为单位）
				const diffInMinutes = (eventTime - currentTime) / (1000 * 60); // 转换为分钟
				
				if (diffInMinutes >= 0) {
				    this.whatColor = 'green'; // 时间大于等于当前时间
				} else if (diffInMinutes < 0 && diffInMinutes >= -60) {
				    this.whatColor = 'yellow'; // 时间小于当前时间但60分钟内
				} else {
				    this.whatColor = 'red'; // 时间小于当前时间但60分钟外
				}
			}
		}
	}
</script>

<style scoped>
	.head {
		position: relative;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background: #1976D2;
		width: 518rpx;
		height: 189rpx;
		margin: auto;
	}
	.title {
		font-size: 48rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #FFFFFF;
	}
	
	.head_left_bottom, .head_right_bottom {
		position: absolute;
		width: 10rpx;
		height: 10rpx;
		z-index: 1;
		background: #F8F8F8;
	}
	
	.head_left_bottom {
		left: -1px;
		bottom: -1px;
		border-radius: 0 10rpx 0 0;
	}
 
	.head_right_bottom {
		right: -1px;
		bottom: -1px;
		border-radius: 10rpx 0 0 0;
	}
	
	.body {
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
		background: #FFFFFF;
		width: 518rpx;
		height: 549rpx;
		margin: auto;
		border-radius: 20rpx 20rpx 0 0;
	}
	
	.body_left_bottom, .body_right_bottom {
		position: absolute;
		width: 30rpx;
		height: 30rpx;
		z-index: 1;
		background: #F8F8F8;
	}
	
	.body_left_bottom {
		left: -1px;
		bottom: -1px;
		border-radius: 0 30rpx 0 0;
	}
	
	.body_right_bottom {
		right: -1px;
		bottom: -1px;
		border-radius: 30rpx 0 0 0;
	}
	
	.body-logo {
		position: absolute;
		top: -36rpx;
		margin: auto;
		width: 98rpx;
		height: 98rpx;
		border-radius: 10%;
	}
	
	.code-img {
		width: 414rpx;
		height: 414rpx;
	}
	
	.door-setting {
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #FF1976;
		padding: 10rpx;
		background-color: #FFDAED;
		width: 518rpx;
		margin: auto;
		margin-top: 25rpx;
	}
	
	.task-go {
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #1EB500;
		padding: 10rpx;
		background-color: #AFECB2;
		width: 518rpx;
		margin: auto;
		margin-top: 25rpx;
	}
	
	.foot-title {
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #8C8C8C;
		padding-top: 30rpx;
		text-align: center;
	}
	
	.foot-btn {
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 112rpx;
		border-top: 1rpx solid #F5F5F5;
		background: #fff;
	}
	
	.slot-content {
		padding: 30rpx;
		font-size: 15px;
	}
</style>
